package ArrayList

import (
	"errors"
	"fmt"
)

type List interface {
	Size() int                               //数组大小
	Get(index int) (interface{}, error)      //获取
	Set(index int, val interface{}) error    //修改数据
	Insert(index int, val interface{}) error //插入
	Append(val interface{})                  //追加
	Delete(index int) error                  //删除
	Clear()                                  //清空
	Last() interface{}                       //最后一个数据
	String() string                          //返回字符串
	Iterator() Iterator
}

type ArrayList struct {
	dataStore [] interface{} //数组存储
	theSize   int            //数组大小
}

func NewArrayList() List {
	list := new(ArrayList)
	//make 中间的参数： 0  表示没有开辟内存
	list.dataStore = make([]interface{}, 0, 10) //开辟10个
	list.theSize = 0
	return list
}

func (list *ArrayList) Size() int {
	return list.theSize //返回数组的大小
}

func (list *ArrayList) Get(index int) (interface{}, error) {
	if index < 0 || index > list.theSize {
		return nil, errors.New("索引越界")
	}
	return list.dataStore[index], nil
}

func (list *ArrayList) Set(index int, val interface{}) error {
	if index < 0 || index > list.theSize {
		return errors.New("索引越界")
	}
	list.dataStore[index] = val
	return nil
}

func (list *ArrayList) Insert(index int, val interface{}) error {
	if index < 0 || index > list.theSize {
		return errors.New("索引越界")
	}

	list.checkIsFull()                               //检查内存，如果满了自动追加
	list.dataStore = list.dataStore[:list.theSize+1] //插入数据，内存移动一位
	for i := list.theSize; i > index; i-- { //从后往前移动
		list.dataStore[i] = list.dataStore[i-1]
	}
	list.dataStore[index] = val //插入数据
	list.theSize++              //索引追加
	return nil
}

func (list *ArrayList) Clear() {
	list.dataStore = make([]interface{}, 0, 10) //开辟10个
	list.theSize = 0
}

func (list *ArrayList) Delete(index int) error {
	if index < 0 || index > list.theSize {
		return errors.New("索引越界")
	}
	list.dataStore = append(list.dataStore[:index], list.dataStore[index+1:]...)
	list.theSize --
	return nil
}

func (list *ArrayList) Append(val interface{}) {
	list.dataStore = append(list.dataStore, val)
	list.theSize++
}

func (list *ArrayList) Last() interface{} {
	return list.dataStore[list.theSize-1]
}

func (list *ArrayList) String() string {
	return fmt.Sprint(list.dataStore)
}

func (list *ArrayList) checkIsFull() {
	if list.theSize == cap(list.dataStore) { //判断内存的使用
		//make 中间的参数： 0  表示没有开辟内存
		newDataStore := make([]interface{}, 2*list.theSize, 2*list.theSize) //开辟双倍内存
		copy(newDataStore, list.dataStore)
		//for i:=0;i<len(list.dataStore);i++{
		//	newDataStore[i] = list.dataStore[i]
		//}
		list.dataStore = newDataStore
	}
}
